﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class TK_LogisticsRegisterInterfaceBusiness : _17TRACK_Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //获取详情接口
        public Base_InterfaceOption Gettrackinfo;
        //推送接口
        public Base_InterfaceOption Push;
        //注册接口
        public Base_InterfaceOption Register;

        //注册接口
        public List<_17TRACK_ReqDTO> ReqData;
        public TK_LogisticsRegisterInterfaceBusiness()
        {
            this.InterfaceName = "17TRACK物流单注册";
            //索引字段
            this.tableField = GetMapField("Push");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            this.Gettrackinfo = this.interfaceOption.Where(x => x.OperateType == "Gettrackinfo").First();
            this.Push = this.interfaceOption.Where(x => x.OperateType == "Push").First();
            this.Register = this.interfaceOption.Where(x => x.OperateType == "Register").First();
            this.ReqData = new List<_17TRACK_ReqDTO>();
            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="EC_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, _17TRACK_NoQueryEventArgs EC_NoQueryEventArgs)
        {
            try
            {
                //获取请求的参数
                EC_NoQueryEventArgs.HttpHeader.Headers.Add("17token", Gettrackinfo.TargetToken);
                //API请求是否成功
                EC_NoQueryEventArgs.Success = EC_NoQueryEventArgs.Result["success"].ToString().ToBool();
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, _17TRACK_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取请求的参数
                queryEventArgs.HttpHeader.Headers.Add("17token", Push.TargetToken);
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, _17TRACK_QueryEventArgs queryEventArgs)
        {
            try
            {
                //设置查询的物流单号
                queryEventArgs.reqData_item.Clear();
                queryEventArgs.reqData_item.AddRange(ReqData.Take(35));

            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, _17TRACK_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                Logistics result = (Logistics)JsonConvert.DeserializeObject<Logistics>(queryEventArgs.ResultStr);
                queryEventArgs.Success = true;
                List<TK_data> temp = new List<TK_data>();
                temp.Add(result.data);
                if (result.data.accepted.Count > 0 || result.data.rejected.Count > 0) queryEventArgs.Rows = temp;
                this.ReqData = this.ReqData.Skip(35).ToList();
                if (this.ReqData.Count <= 0) queryEventArgs.Page.Complete = true;
                Thread.Sleep(3000);
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            try
            {
                //获取ONE_LINK多平台订单物流单号
                OrderDetailInterfaceBusiness eC_OrderList = new OrderDetailInterfaceBusiness();
                eC_OrderList.Filters.Clear();
                eC_OrderList.Filters.Add(
               //13:>,14>=15:<,16<=
               new OL_FilterDTO() { ControlId = "676bb02a9e0bc69bf1a75be8", DataType = 2, SpliceType = 1, FilterType = 8, Value = "" });//物流单号不为空
                eC_OrderList.Filters.Add(
               //13:>,14>=15:<,16<=
               new OL_FilterDTO() { ControlId = "6880cffba31d84c7f68e48c6", DataType = 29, SpliceType = 1, FilterType = 7, Value = "" });//尾程信息为空

                List<order_details> ec_OrderLIsts = await eC_OrderList.QueryAsync<order_details>(eC_OrderList.queryOption, eC_OrderList.tableField, eC_OrderList.SqlDb);


                //获取ONE_LINK退货管理物流单号
                OL_ReturnMagInterfaceBusiness OL_ReturnMag = new OL_ReturnMagInterfaceBusiness();
                List<ReturnMag> OL_ReturnMags = await OL_ReturnMag.GetRows();

                //获取ONE_LINK配件管理物流单号
                OL_AccessoryMagInterfaceBusiness OL_AccessoryMag = new OL_AccessoryMagInterfaceBusiness();
                List<OL_AccessoryMag> OL_AccessoryMags = await OL_AccessoryMag.GetRows();

                //获取ONE_LINK换货管理物流单号
                //退货的数据
                OL_ExchangeMagInterfaceBusiness OL_ExchangeMag = new OL_ExchangeMagInterfaceBusiness();
                OL_ExchangeMag.Filters.Clear();
                OL_ExchangeMag.Filters.Add(
               new OL_FilterDTO() { ControlId = "66ce7f941214257ad13bf253", DataType = 2, SpliceType = 1, FilterType = 8, Value = "" }//人工填写跟踪号不为空(退货)
           );
                OL_ExchangeMag.Filters.Add(
                   //13:>,14>=15:<,16<=
                   new OL_FilterDTO() { ControlId = "68c7a92f075cb3166a16bb3f", DataType = 29, SpliceType = 1, FilterType = 7, Value = "" }//系统关联物流信息为空(退货)
               );
                List<OL_ExchangeMag> OL_ExchangeMags_Return = await OL_ExchangeMag.GetRows();

                //换货的数据
                OL_ExchangeMag.Filters.Clear();
                OL_ExchangeMag.Filters.Add(
                   new OL_FilterDTO() { ControlId = "66ce7f941214257ad13bf254", DataType = 2, SpliceType = 1, FilterType = 8, Value = "" }//人工填写跟踪号不为空(换货)
               );
                OL_ExchangeMag.Filters.Add(
                   //13:>,14>=15:<,16<=
                   new OL_FilterDTO() { ControlId = "68c91ebc075cb3166a1ade74", DataType = 29, SpliceType = 1, FilterType = 7, Value = "" }//系统关联物流信息为空(换货)
               );
                List<OL_ExchangeMag> OL_ExchangeMags_Change = await OL_ExchangeMag.GetRows();


                //注册物流单号
                if (ec_OrderLIsts.Count > 0 || OL_ReturnMags.Count > 0 || OL_ExchangeMags_Change.Count > 0 || OL_ExchangeMags_Return.Count > 0 || OL_AccessoryMags.Count > 0)
                {

                    #region 查询物流单号详情
                    //ONE_LINK多平台跟踪号(物流单号)
                    List<string> orderNum_T = ec_OrderLIsts.Select(x => x.shipping_method_no).ToList().ToList();
                    //ONE_LINK退货管理物流单(物流单号)
                    List<string> orderNum_T2 = OL_ReturnMags.Select(x => x.ExpOrder).ToList().ToList();
                    //ONE_LINK换货管理物流单(退货物流单号)
                    var items1 = OL_ExchangeMags_Return.Select(x => x.ExpOrder_Reture).ToList().ToList();
                    orderNum_T2.AddRange(items1);
                    //ONE_LINK换货管理物流单(换货物流单号)
                    var items2 = OL_ExchangeMags_Change.Select(x => x.ExpOrder_Change).ToList().ToList();
                    orderNum_T2.AddRange(items2);
                    //ONE_LINK配件管理物流单(物流单号)
                    var items3 = OL_AccessoryMags.Select(x => x.ExpOrder).ToList().ToList();
                    orderNum_T2.AddRange(items3);
                    orderNum_T2 = orderNum_T2.Where(x => !x.IsNullOrEmpty()).ToList();
                    List<string> orderNum_T2_ = new List<string>();
                    for (int i = 0; i < orderNum_T2.Count; i++)
                    {
                        //if (orderNum_T2[i].Contains("791608745381") || orderNum_T2[i].Contains("791608744960") || orderNum_T2[i].Contains("771380347725") || orderNum_T2[i].Contains("791604960988"))
                        //{
                        //    var ee = orderNum_T2[i];

                        //}
                        if (orderNum_T2[i].Contains(","))
                        {
                            orderNum_T2_.AddRange(orderNum_T2[i].Split(",").ToList());
                        }
                        else
                        {
                            orderNum_T2_.Add(orderNum_T2[i]);
                        }
                    }
                    orderNum_T2 = orderNum_T2_;
                    //合并物流单号
                    orderNum_T.AddRange(orderNum_T2);
                    orderNum_T = orderNum_T.Distinct().ToList();

                    this.ReqData.Clear();
                    foreach (var item1 in orderNum_T)
                    {
                        _17TRACK_ReqDTO temp = new _17TRACK_ReqDTO();
                        temp.number = item1;
                        this.ReqData.Add(temp);
                    }
                    //获取17tk已注册的订单号
                    List<TK_data> get = await this.QueryAsync<TK_data>(this.Gettrackinfo, this.SqlDb);
                    List<string> orderNum_S = new List<string>();
                    foreach (var item1 in get)
                    {
                        orderNum_S.AddRange(item1.accepted.Select(x => x.number).ToList());
                    }
                    //差异项
                    List<string> diff = orderNum_T.Except(orderNum_S).Where(x => !x.IsNullOrEmpty()).ToList();
                    #endregion
                    var SS = string.Join(",", diff);
                    #region 注册物流单号
                    if (orderNum_S.Count > 0 && diff.Count > 0)
                    {
                        //第一次注册:不带运输商
                        this.ReqData.Clear();
                        foreach (var item1 in diff)
                        {
                            _17TRACK_ReqDTO temp = new _17TRACK_ReqDTO();
                            temp.number = item1;
                            this.ReqData.Add(temp);
                        };
                        List<TK_data> reg = await this.QueryAsync<TK_data>(this.Register, this.SqlDb);
                        //第二次注册:获取注册失败的配置运输商代码再次请求
                        this.ReqData.Clear();
                        foreach (var item1 in reg)
                        {
                            //运营商赋值
                            item1.rejected.ForEach(x =>
                            {
                                if (x.error.code != "-18019901")//已经注册过的不需再次注册
                                {

                                    _17TRACK_ReqDTO temp = new _17TRACK_ReqDTO();
                                    temp.number = x.number;
                                    temp.carrier = "100003";
                                    this.ReqData.Add(temp);


                                }


                            });
                        }
                        reg = await this.QueryAsync<TK_data>(this.Register, this.SqlDb);


                        #region 推送物流单号
                        //this.ReqData.Clear();
                        //foreach (var item1 in diff)
                        //{
                        //    _17TRACK_ReqDTO temp = new _17TRACK_ReqDTO();
                        //    temp.number = item1;
                        //    this.ReqData.Add(temp);
                        //};
                        //List<object> pus = await this.QueryAsync<object>(this.Push, this.SqlDb);
                        #endregion
                    }
                    #endregion
                }

            }
            catch (Exception ex)
            {
                AddLog(this.SqlDb, ex.Message, InterfaceName, this.Push.OperateType);
            }
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
